﻿//using Newtonsoft.Json;
//using System;
//using System.Collections.Generic;
//using System.IO;
//using System.Linq;
//using System.Net;
//using System.Net.Http;
//using System.Net.Http.Headers;
//using System.Threading.Tasks;
//using System.Web.Http;
//using WebApi_SY.Entity;
//using WebApi_SY.Models;

//namespace WebApi_SY.Controllers
//{
//    public class sli_document_quality_standardController : ApiController
//    {
//        [HttpPost]
//        public async Task<IHttpActionResult> InsertData()
//        {
//            try
//            {
//                //var context = new YourDbContext();
//                if (!Request.Content.IsMimeMultipartContent())
//                {
//                    return BadRequest("Expected multipart/form-data request.");
//                }

//                var standard = new sli_document_quality_standard();
//                List<sli_document_quality_standardBillEntry> entryList = new List<sli_document_quality_standardBillEntry>();
//                List<sli_document_quality_standardBill> billList = new List<sli_document_quality_standardBill>();
//                List<sli_document_quality_standardAttachment> attachmentList = new List<sli_document_quality_standardAttachment>();
//                //var entry = new sli_document_tech_saleBillEntry();
//                //var attachment = new sli_document_tech_saleAttachment();
//                using (var dbContext = new YourDbContext())
//                {
//                    var provider = new MultipartMemoryStreamProvider();
//                    var task = Request.Content.ReadAsMultipartAsync(provider);
//                    //task.Wait();
//                    await task;
//                    foreach (var content in provider.Contents)
//                    {
//                        var contentDisposition = content.Headers.ContentDisposition;

//                        if (contentDisposition.Name.Trim('\"').StartsWith("Sale"))
//                        {
//                            var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Sale".Length).Trim('[', ']').Split('=');
//                            if (keyValuePairs.Length == 1)
//                            {
//                                var propertyName = keyValuePairs[0];
//                                var propertyValue = content.ReadAsStringAsync().Result;

//                                dynamic sale1 = JsonConvert.DeserializeObject(propertyValue);

//                                standard.Fnumber = sale1.Fnumber;
//                                standard.Fname = sale1.Fname;
//                                standard.Fdate = sale1.Fdate;
//                                if (Convert.ToString( sale1.FmaterialID) =="")
//                                {
//                                    standard.FmaterialID = 0;
//                                }
//                                else
//                                {
//                                    standard.FmaterialID = sale1.FmaterialID;
//                                }

//                                standard.FcustomerID = sale1.FcustomerID;

//                                dbContext.Sli_document_quality_standard.Add(standard);
//                                dbContext.SaveChanges();
//                            }
//                        }
//                        else if (contentDisposition.Name.Trim('\"').StartsWith("Bill"))
//                        {
//                            // 解析子表1数据
//                            var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Bill".Length).Trim('[', ']').Split('=');
//                            if (keyValuePairs.Length == 1)
//                            {
//                                var propertyName = keyValuePairs[0];
//                                var propertyValue = content.ReadAsStringAsync().Result;

//                                dynamic Bill1 = JsonConvert.DeserializeObject(propertyValue);

//                                foreach (var billItem in Bill1)
//                                {
//                                    var ftechOptionID1 = 0;

//                                    if (Convert.ToString( billItem.fqualityOptionID) == "")
//                                    {
//                                        ftechOptionID1 = 0;
//                                    }
//                                    else
//                                    {
//                                        ftechOptionID1 = billItem.fqualityOptionID;
//                                    }
//                                    billList.Add(new sli_document_quality_standardBill
//                                    {
//                                        fmainID = standard.Id,
//                                        fqualityOptionID = ftechOptionID1,
//                                        fnote = billItem.fnote
//                                    });
//                                }




//                            }
//                        }
//                        else if (contentDisposition.Name.Trim('\"').StartsWith("Entry"))
//                        {
//                            // 解析子表2数据
//                            var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Entry".Length).Trim('[', ']').Split('=');
//                            if (keyValuePairs.Length == 1)
//                            {
//                                var propertyName = keyValuePairs[0];
//                                var propertyValue = content.ReadAsStringAsync().Result;
//                                dynamic Entry1 = JsonConvert.DeserializeObject(propertyValue);

//                                foreach (var entryItem in Entry1)
//                                {
//                                    var ftechObjectID1 = 0;

//                                    if (Convert.ToString(entryItem.fqualityObjectID) == "")
//                                    {
//                                        ftechObjectID1 = 0;
//                                    }
//                                    else
//                                    {
//                                        ftechObjectID1 = entryItem.fqualityObjectID;
//                                    }
//                                    entryList.Add(new sli_document_quality_standardBillEntry
//                                    {
//                                        fbillID = standard.Id,
//                                        fqualityObjectID = ftechObjectID1,
//                                        fnote = entryItem.fnote,
//                                        ftarget = entryItem.ftarget,
//                                        fmin = entryItem.fmin,
//                                        fmax = entryItem.fmax
//                                    });
//                                }

//                            }
//                        }
//                        else if (contentDisposition.Name.Trim('\"').StartsWith("Files"))
//                        {
//                            if (contentDisposition.Name.Trim('\"').EndsWith("Files"))
//                            {
//                                var fileName = Path.GetFileName(content.Headers.ContentDisposition.FileName.Trim('\"'));
//                                var fileData = content.ReadAsByteArrayAsync().Result;
//                                attachmentList.Add(new sli_document_quality_standardAttachment
//                                {
//                                    fattachment = fileName,
//                                    fileData = fileData,
//                                    fmainID = standard.Id
//                                });

//                            }

//                        }
//                        //return contentDisposition.Name;
//                    }

//                    // 添加子表
//                    dbContext.Sli_document_quality_standardBill.AddRange(billList);
//                    dbContext.Sli_document_quality_standardBillEntry.AddRange(entryList);
//                    dbContext.Sli_document_quality_standardAttachment.AddRange(attachmentList);
//                    // dbContext.SaveChanges();

//                    dbContext.SaveChanges();



//                }



//                var data = new
//                {
//                    code = 200,
//                    msg = "ok",
//                    Id = standard.Id,
//                    date = standard.Id + "保存成功"

//                };
//                return Ok(data);
//            }
//            catch (Exception ex)
//            {
//                return Ok(ex.ToString());
//            }
//        }


//        [HttpPost]
//        public async Task<IHttpActionResult> UpdateData(int id)
//        {
//            if (!Request.Content.IsMimeMultipartContent())
//            {
//                return BadRequest("Expected multipart/form-data request.");
//            }

//            var standard = new sli_document_quality_standard();
//            List<sli_document_quality_standardBillEntry> entryList = new List<sli_document_quality_standardBillEntry>();
//            List<sli_document_quality_standardBill> billList = new List<sli_document_quality_standardBill>();
//            List<sli_document_quality_standardAttachment> attachmentList = new List<sli_document_quality_standardAttachment>();


//            using (var dbContext = new YourDbContext())
//            {
//                var existingbill = dbContext.Sli_document_quality_standardBill.Where(b => b.fmainID == id);
//                dbContext.Sli_document_quality_standardBill.RemoveRange(existingbill);
//                var existingEntry = dbContext.Sli_document_quality_standardBillEntry.Where(b => b.fbillID == id);
//                dbContext.Sli_document_quality_standardBillEntry.RemoveRange(existingEntry);
//                var existingachment = dbContext.Sli_document_quality_standardAttachment.Where(b => b.fmainID == id);
//                dbContext.Sli_document_quality_standardAttachment.RemoveRange(existingachment);
//                dbContext.SaveChanges();

//                var provider = new MultipartMemoryStreamProvider();
//                var task = Request.Content.ReadAsMultipartAsync(provider);
//                //task.Wait();
//                await task;
//                foreach (var content in provider.Contents)
//                {
//                    var contentDisposition = content.Headers.ContentDisposition;

//                    if (contentDisposition.Name.Trim('\"').StartsWith("Sale"))
//                    {
//                        var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Sale".Length).Trim('[', ']').Split('=');
//                        if (keyValuePairs.Length == 1)
//                        {
//                            var propertyName = keyValuePairs[0];
//                            var propertyValue = content.ReadAsStringAsync().Result;

//                            dynamic sale1 = JsonConvert.DeserializeObject(propertyValue);
//                            var existing = dbContext.Sli_document_quality_standard.Find(id);
//                            existing.Fnumber = sale1.Fnumber;
//                            existing.Fname = sale1.Fname;
//                            existing.FmaterialID = Convert.ToInt32(sale1.FmaterialID);
//                            existing.FcustomerID = sale1.FcustomerID;


//                            //sale.Fstatus = sale1.Fstatus;
//                            //if (sale1.ForderNo == "")
//                            //{
//                            //    sale.ForderNo = 0;
//                            //}
//                            //else
//                            //{
//                            //    sale.ForderNo = int.Parse(sale1.ForderNo);
//                            //}

//                            //sale.FstandardNo = sale1.FstandardNo;

//                            //sale.Ftaxtrue = sale1.Ftaxtrue;
//                            //dbContext.Sli_document_tech_sale.Add(existing);
//                            dbContext.SaveChanges();
//                            //var id = sale1.id;
//                            var temp = sale1.sli_document_quality_standardAttachment_view;
//                            if (temp.Count > 0)
//                            {
//                                foreach (var tempitem in temp)
//                                {
//                                    attachmentList.Add(new sli_document_quality_standardAttachment
//                                    {
//                                        fattachment = tempitem.fattachment,
//                                        fileData = tempitem.fileData,
//                                        fmainID = id
//                                    });
//                                    dbContext.Sli_document_quality_standardAttachment.AddRange(attachmentList);

//                                }
//                            }
//                            //dbContext.SaveChanges();

//                        }
//                    }
//                    else if (contentDisposition.Name.Trim('\"').StartsWith("Bill"))
//                    {
//                        // 解析子表1数据
//                        var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Bill".Length).Trim('[', ']').Split('=');
//                        if (keyValuePairs.Length == 1)
//                        {
//                            var propertyName = keyValuePairs[0];
//                            var propertyValue = content.ReadAsStringAsync().Result;

//                            dynamic Bill1 = JsonConvert.DeserializeObject(propertyValue);

//                            foreach (var billItem in Bill1)
//                            {
//                                var ftechOptionID1 = 0;
//                                if (billItem.fqualityOptionID is null)
//                                {
//                                    ftechOptionID1 = 0;
//                                }
//                                else
//                                {
//                                    ftechOptionID1 = Convert.ToInt32(billItem.fqualityOptionID);
//                                }

//                                billList.Add(new sli_document_quality_standardBill
//                                {
//                                    fmainID = id,
//                                    fqualityOptionID = ftechOptionID1,
//                                    fnote = billItem.fnote
//                                });
//                            }




//                        }
//                    }
//                    else if (contentDisposition.Name.Trim('\"').StartsWith("Entry"))
//                    {
//                        // 解析子表2数据
//                        var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Entry".Length).Trim('[', ']').Split('=');
//                        if (keyValuePairs.Length == 1)
//                        {
//                            var propertyName = keyValuePairs[0];
//                            var propertyValue = content.ReadAsStringAsync().Result;
//                            dynamic Entry1 = JsonConvert.DeserializeObject(propertyValue);

//                            foreach (var entryItem in Entry1)
//                            {
//                                var ftechObjectID1 = 0;
//                                if (entryItem.fqualityObjectID is null)
//                                {
//                                    ftechObjectID1 = 0;
//                                }
//                                else
//                                {
//                                    ftechObjectID1 = Convert.ToInt32(entryItem.fqualityObjectID);
//                                }
//                                entryList.Add(new sli_document_quality_standardBillEntry
//                                {
//                                    fbillID = id,
//                                    fqualityObjectID = ftechObjectID1,
//                                    fnote = entryItem.fnote,
//                                    ftarget = entryItem.ftarget,
//                                    fmin = entryItem.fmin,
//                                    fmax = entryItem.fmax
//                                });
//                            }

//                        }
//                    }
//                    else if (contentDisposition.Name.Trim('\"').StartsWith("Files"))
//                    {
//                        if (contentDisposition.Name.Trim('\"').EndsWith("Files"))
//                        {
//                            var fileName = Path.GetFileName(content.Headers.ContentDisposition.FileName.Trim('\"'));
//                            var fileData = content.ReadAsByteArrayAsync().Result;
//                            attachmentList.Add(new sli_document_quality_standardAttachment
//                            {
//                                fattachment = fileName,
//                                fileData = fileData,
//                                fmainID = id
//                            });

//                        }

//                    }
//                    //return contentDisposition.Name;
//                }

//                // 添加子表
//                dbContext.Sli_document_quality_standardBill.AddRange(billList);
//                dbContext.Sli_document_quality_standardBillEntry.AddRange(entryList);
//                dbContext.Sli_document_quality_standardAttachment.AddRange(attachmentList);
//                // dbContext.SaveChanges();

//                dbContext.SaveChanges();



//            }
//            var data = new
//            {
//                code = 200,
//                msg = "ok",
//                Id = id,
//                date = id + "修改成功"

//            };
//            return Ok(data);

//        }


//        [System.Web.Http.HttpPost]
//        public async Task<object> Delete(List<int> id)
//        {
//            try
//            {
//                foreach (var deleteid in id)
//                {
//                    var context = new YourDbContext();
//                    var entity = await context.Sli_document_quality_standard.FindAsync(deleteid);
//                    if (entity == null)
//                    {
//                        var dataNull = new
//                        {
//                            code = 200,
//                            msg = "ok",
//                            Id = id.ToString(),
//                            date = id.ToString() + "不存在"
//                        };
//                        //string json = JsonConvert.SerializeObject(data);
//                        return dataNull;
//                    }

//                    var existingbill = context.Sli_document_quality_standardBill.Where(b => b.fmainID == deleteid);
//                    context.Sli_document_quality_standardBill.RemoveRange(existingbill);
//                    var existingEntry = context.Sli_document_quality_standardBillEntry.Where(b => b.fbillID == deleteid);
//                    context.Sli_document_quality_standardBillEntry.RemoveRange(existingEntry);
//                    var existingachment = context.Sli_document_quality_standardAttachment.Where(b => b.fmainID == deleteid);
//                    context.Sli_document_quality_standardAttachment.RemoveRange(existingachment);
//                    context.Sli_document_quality_standard.RemoveRange(entity);
//                    await context.SaveChangesAsync();

//                }

//                // var data = new { Status = "Success", Message = "Data retrieved successfully", Data = new { /* actual data here */ } };
//                var data = new
//                {
//                    code = 200,
//                    msg = "Success",
//                    //orderId = id.ToString(),
//                    date = "删除成功"
//                };
//                return data;
//            }
//            catch (Exception ex)
//            {
//                var data = new
//                {
//                    code = 400,
//                    msg = "失败",
//                    orderId = id.ToString(),
//                    date = ex.ToString()
//                };
//                return data;
//            }


//        }

//        [HttpGet]
//        public IHttpActionResult GetTableBydocument_tech_saleAttachment(int? id = null)
//        {
//            try
//            {
//                var context = new YourDbContext();

//                var attachment = context.Sli_document_quality_standardAttachment.FirstOrDefault(a => a.id == id);
//                if (attachment == null)
//                {
//                    return NotFound();
//                }

//                // 将字节数组转换为流
//                var stream = new MemoryStream(attachment.fileData);
//                // 返回文件流作为响应，并设置适当的内容类型和文件名
//                var response = new HttpResponseMessage()
//                {
//                    Content = new StreamContent(stream),
//                    StatusCode = HttpStatusCode.OK
//                };
//                response.Content.Headers.ContentType = new MediaTypeHeaderValue(GetContentType(attachment.fattachment));
//                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
//                {
//                    FileName = attachment.fattachment
//                };

//                return ResponseMessage(response);
//                // 返回文件流作为响应



//            }
//            catch (Exception ex)
//            {
//                return InternalServerError(ex);
//            }


//        }

//        private string GetContentType(string fileName)
//        {
//            var extension = System.IO.Path.GetExtension(fileName);
//            switch (extension)
//            {
//                case ".pdf":
//                    return "application/pdf";
//                case ".jpg":
//                case ".jpeg":
//                    return "image/jpeg";
//                case ".png":
//                    return "image/png";
//                case ".doc":
//                    return "application/msword";
//                case ".docx":
//                    return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
//                // 添加更多文件类型的处理
//                default:
//                    return "application/octet-stream";
//            }
//        }

//        [HttpGet]
//        public IHttpActionResult GetTableBydocument_quality_standard(int page = 1, int pageSize = 10, string fnumber = null, string fname = null)
//        {
//            try
//           {
//                var context = new YourDbContext();
//                IQueryable<sli_document_quality_standard_view> query = context.Sli_document_quality_standard_view;

//                if (!string.IsNullOrEmpty(fnumber))
//                {
//                    query = query.Where(q => q.Fnumber.Contains(fnumber));
//                }

//                if (!string.IsNullOrEmpty(fname))
//                {
//                    query = query.Where(q => q.Fname.Contains(fname));
//                }
//                var totalCount = query.Count(); //记录数
//                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 页数
//                var paginatedQuery = query.OrderByDescending(b => b.Id).Skip((page - 1) * pageSize).Take(pageSize); //  某页记录
//                                                                                                                    //var datas = query.ToList();
//                var response = new    // 定义 前端返回数据  总记录，总页，当前页 ，size,返回记录
//                {
//                    code = 200,
//                    msg = "OK",
//                    data = new
//                    {
//                        totalCounts = totalCount,
//                        totalPagess = totalPages,
//                        currentPages = page,
//                        pageSizes = pageSize,
//                        data = paginatedQuery
//                    }


//                };

//                return Json(response);
//            }
//            catch (Exception ex)
//            {
//                return InternalServerError(ex);
//            }
//        }

//        [HttpGet]
//        public IHttpActionResult GetTableBydocument_quality_standardall(int? id = null)
//        {
//            try
//            {
//                var context = new YourDbContext();

//                var techSale = context.Sli_document_quality_standard_view.Find(id);

//                techSale.sli_document_quality_standardBill_view = context.Sli_document_quality_standardBill_view.Where(st1 => st1.fmainID == id).ToList() ?? new List<sli_document_quality_standardBill_view>();
//                techSale.sli_document_quality_standardBillEntry_view = context.Sli_document_quality_standardBillEntry_view.Where(st2 => st2.fbillID == id).ToList() ?? new List<sli_document_quality_standardBillEntry_view>();
//                techSale.sli_document_quality_standardAttachment_view = context.Sli_document_quality_standardAttachment_view.Where(st3 => st3.fmainID == id).ToList() ?? new List<sli_document_quality_standardAttachment_view>();


//                var result = new List<object>();


//                result.Add(new
//                {
//                    Sli_document_tech_sale = techSale,

//                });

//                var response = new    // 定义 前端返回数据  总记录，总页，当前页 ，size,返回记录
//                {
//                    code = 200,
//                    msg = "OK",
//                    data = new
//                    {

//                        data = result
//                    }
//                };

//                return Ok(response);

//            }
//            catch (Exception ex)
//            {
//                return Ok(ex.ToString());
//            }
//        }

//    }
//}
//----------------------------******************************------------------------------------------
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi_SY.Entity;
using WebApi_SY.Models;

namespace WebApi_SY.Controllers
{
    public class sli_document_quality_standardController : ApiController
    {
        [HttpPost]
        public async Task<IHttpActionResult> InsertData()
        {
            #region
            //try
            //{
            //    if (!Request.Content.IsMimeMultipartContent())
            //    {
            //        return BadRequest("Unsupported media type.");
            //    }

            //    var provider = new MultipartMemoryStreamProvider();
            //    await Request.Content.ReadAsMultipartAsync(provider);

            //    // 处理主表数据
            //    var salePart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Sale");
            //    if (salePart == null) return BadRequest("Missing Sale data");

            //    var saleJson = await salePart.ReadAsStringAsync();
            //    var standard = JsonConvert.DeserializeObject<sli_document_quality_standard>(saleJson);

            //    // 处理子表数据
            //    var billPart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Bill");
            //    var billModels = billPart != null
            //        ? JsonConvert.DeserializeObject<List<sli_document_quality_standardBill>>(await billPart.ReadAsStringAsync())
            //        : new List<sli_document_quality_standardBill>();

            //    var entryPart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Entry");
            //    var entryModels = entryPart != null
            //        ? JsonConvert.DeserializeObject<List<sli_document_quality_standardBillEntry>>(await entryPart.ReadAsStringAsync())
            //        : new List<sli_document_quality_standardBillEntry>();

            //    // 处理附件
            //    var fileParts = provider.Contents.Where(c => c.Headers.ContentDisposition.Name.Trim('"') == "Files");
            //    var attachments = new List<sli_document_quality_standardAttachment>();

            //    using (var context = new YourDbContext())
            //    using (var transaction = context.Database.BeginTransaction())
            //    {
            //        try
            //        {
            //            // 保存主表
            //            context.Sli_document_quality_standard.Add(standard);
            //            await context.SaveChangesAsync();

            //            // 处理子表1
            //            billModels.ForEach(b => b.fmainID = standard.Id);
            //            context.Sli_document_quality_standardBill.AddRange(billModels);

            //            // 处理子表2
            //            entryModels.ForEach(e => e.fbillID = standard.Id);
            //            context.Sli_document_quality_standardBillEntry.AddRange(entryModels);

            //            // 处理附件
            //            foreach (var filePart in fileParts)
            //            {
            //                var fileName = filePart.Headers.ContentDisposition.FileName.Trim('"');
            //                var fileData = await filePart.ReadAsByteArrayAsync();
            //                attachments.Add(new sli_document_quality_standardAttachment
            //                {
            //                    fmainID = standard.Id,
            //                    fattachment = fileName,
            //                    fileData = fileData
            //                });
            //            }
            //            context.Sli_document_quality_standardAttachment.AddRange(attachments);

            //            await context.SaveChangesAsync();
            //            transaction.Commit();

            //            return Ok(new
            //            {
            //                code = 200,
            //                msg = "ok",
            //                Id = standard.Id,
            //                date = $"{standard.Id}保存成功"
            //            });
            //        }
            //        catch (Exception ex)
            //        {
            //            transaction.Rollback();
            //            return BadRequest($"Transaction error: {ex.Message}");
            //        }

            //    }
            //}
            //catch (JsonException ex)
            //{
            //    return BadRequest($"JSON parsing error: {ex.Message}");
            //}
            //catch (DbUpdateException ex)
            //{
            //    return BadRequest($"Database update error: {ex.InnerException?.Message ?? ex.Message}");
            //}
            //catch (Exception ex)
            //{
            //    return InternalServerError(ex);
            //}
            #endregion
            try
            {
                #region
                ////var context = new YourDbContext();
                //if (!Request.Content.IsMimeMultipartContent())
                //{
                //    return BadRequest("Expected multipart/form-data request.");
                //}

                //var sale = new sli_document_process_model();
                //var bill = new sli_document_process_modelBill();
                //List<sli_document_process_modelBillEntry> entryList = new List<sli_document_process_modelBillEntry>();
                //List<sli_document_process_modelBill> billList = new List<sli_document_process_modelBill>();
                //List<sli_document_process_modelAttachment> attachmentList = new List<sli_document_process_modelAttachment>();
                //var entry = new sli_document_process_modelBillEntry();
                //var attachment = new sli_document_process_modelAttachment();
                //using (var dbContext = new YourDbContext())
                //{
                //    var provider = new MultipartMemoryStreamProvider();
                //    var task = Request.Content.ReadAsMultipartAsync(provider);
                //    //task.Wait();
                //    //await task;
                //    foreach (var content in provider.Contents)
                //    {
                //        var contentDisposition = content.Headers.ContentDisposition;

                //        if (contentDisposition.Name.Trim('\"').StartsWith("Sale"))
                //        {
                //            var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Sale".Length).Trim('[', ']').Split('=');
                //            if (keyValuePairs.Length == 1)
                //            {
                //                var propertyName = keyValuePairs[0];
                //                var propertyValue = content.ReadAsStringAsync().Result;

                //                dynamic sale1 = JsonConvert.DeserializeObject(propertyValue);

                //                sale.Fnumber = sale1.Fnumber;
                //                sale.Fname = sale1.Fname;
                //                sale.Fdate =sale1.Fdate;
                //                sale.Ftaxtrue = sale1.Ftaxtrue;
                //                sale.Fbillerid = sale1.Fbillerid;
                //                sale.Fstatus = sale1.Fstatus;
                //                dbContext.Sli_document_process_model.Add(sale);
                //                dbContext.SaveChanges();
                //            }
                //        }
                //        else if (contentDisposition.Name.Trim('\"').StartsWith("Bill"))
                //        {
                //            // 解析子表1数据
                //            var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Bill".Length).Trim('[', ']').Split('=');
                //            if (keyValuePairs.Length == 1)
                //            {
                //                var propertyName = keyValuePairs[0];
                //                var propertyValue = content.ReadAsStringAsync().Result;

                //                dynamic Bill1 = JsonConvert.DeserializeObject(propertyValue);

                //                foreach (var billItem in Bill1)
                //                {

                //                    billList.Add(new sli_document_process_modelBill
                //                    {
                //                        Id = sale.Id,
                //                        Foptionid = billItem.Foptionid,
                //                        Fdeptid = billItem.Fdeptid,
                //                        Fnote = billItem.Fnote,
                //                        Fstatus = billItem.Fstatus,
                //                    });
                //                }


                //                dbContext.Sli_document_process_modelBill.AddRange(billList);

                //            }
                //            dbContext.SaveChanges();

                //        }
                //        else if (contentDisposition.Name.Trim('\"').StartsWith("Entry"))
                //        {
                //            // 解析子表2数据
                //            var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Entry".Length).Trim('[', ']').Split('=');
                //            if (keyValuePairs.Length == 1)
                //            {
                //                var propertyName = keyValuePairs[0];
                //                var propertyValue = content.ReadAsStringAsync().Result;
                //                dynamic Entry1 = JsonConvert.DeserializeObject(propertyValue);

                //                foreach (var entryItem in Entry1)
                //                {

                //                    entryList.Add(new sli_document_process_modelBillEntry
                //                    {
                //                        Fbillid = bill.Fbillid,
                //                        Fobjectid = entryItem.Fobjectid,
                //                        Fmax = entryItem.Fmax,
                //                        Fmin = entryItem.Fmin,
                //                        Ftarget = entryItem.Ftarget,
                //                        Fnote = entryItem.Fnote,
                //                        Fnoties = entryItem.Fnoties,
                //                        Fexplanation = entryItem.Fexplanation
                //                    });
                //                }

                //            }
                //        }
                //        else if (contentDisposition.Name.Trim('\"').StartsWith("Files"))
                //        {
                //            if (contentDisposition.Name.Trim('\"').EndsWith("Files"))
                //            {
                //                var fileName = Path.GetFileName(content.Headers.ContentDisposition.FileName.Trim('\"'));
                //                var fileData = content.ReadAsByteArrayAsync().Result;
                //                attachmentList.Add(new sli_document_process_modelAttachment
                //                {
                //                    fattachment = fileName,
                //                    fileData = fileData,
                //                    fmainid = sale.Id
                //                });

                //            }

                //        }

                //    }

                //    // 添加子表

                //    dbContext.Sli_document_process_modelBillEntry.AddRange(entryList);
                //    dbContext.Sli_document_process_modelAttachment.AddRange(attachmentList);
                //    // dbContext.SaveChanges();

                //    dbContext.SaveChanges();



                //}



                //var data = new
                //{
                //    code = 200,
                //    msg = "ok",
                //    Id = sale.Id,
                //    date = sale.Id + "保存成功"

                //};
                //return Ok(data);
                #endregion
                if (!Request.Content.IsMimeMultipartContent())
                {
                    return BadRequest("Unsupported media type.");
                }

                MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
                try
                {
                    await Request.Content.ReadAsMultipartAsync(provider);
                }
                catch (Exception ex)
                {
                    return BadRequest("Error reading multipart content: " + ex.Message);
                }

                var salePart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Sale");
                var billPart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Bill");
                var fileParts = provider.Contents.Where(c => c.Headers.ContentDisposition.Name.Trim('"') == "Files").ToList();

                // 处理 Sale 数据
                string saleJson;
                if (salePart != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        await salePart.CopyToAsync(ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        saleJson = new StreamReader(ms).ReadToEnd();
                    }
                }
                else
                {
                    return BadRequest("Sale data is missing.");
                }
                sli_document_quality_standard saleModel = JsonConvert.DeserializeObject<sli_document_quality_standard>(saleJson);

                // 处理 Bill 数据
                string billJson;
                if (billPart != null)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        await billPart.CopyToAsync(ms);
                        ms.Seek(0, SeekOrigin.Begin);
                        billJson = new StreamReader(ms).ReadToEnd();
                    }
                }
                else
                {
                    return BadRequest("Bill data is missing.");
                }
                var billModels = JsonConvert.DeserializeObject<List<sli_document_quality_standardBill>>(billJson);

                using (var context = new YourDbContext())
                {
                    // 添加主表数据
                    context.Sli_document_quality_standard.Add(saleModel);
                    context.SaveChanges();

                    // 关联并添加中间表和子表数据
                    foreach (var bill in billModels)
                    {
                        bill.sli_document_quality_standard = saleModel;
                        context.Sli_document_quality_standardBill.Add(bill);
                    }
                    context.SaveChanges();

                    //foreach (var entry in billModels.SelectMany(b => b.sli_document_process_modelBillEntry))
                    //{
                    //    entry.sli_document_process_modelBill = billModels.FirstOrDefault(b => b.Fbillid == entry.Fbillid);
                    //    context.Sli_document_process_modelBillEntry.Add(entry);
                    //}
                    //context.SaveChanges();

                    // 处理文件数据

                    foreach (var filePart in fileParts)
                    {
                        string fileName = filePart.Headers.ContentDisposition.FileName.Trim('"');
                        using (MemoryStream fileMs = new MemoryStream())
                        {
                            await filePart.CopyToAsync(fileMs);
                            fileMs.Seek(0, SeekOrigin.Begin);
                            byte[] fileBytes = fileMs.ToArray();
                            var attachment = new sli_document_quality_standardAttachment_view
                            {
                                fmainID = saleModel.Id,
                                fattachment = fileName,
                                fileData = fileBytes
                            };
                            context.Sli_document_quality_standardAttachment_view.Add(attachment);
                            context.SaveChanges();
                        }
                    }
                }
                var data = new
                {
                    code = 200,
                    msg = "ok",
                    Id = saleModel.Id,
                    date = saleModel.Id + "保存成功"

                };

                return Ok(data);
            }
            catch (DbUpdateException ex)
            {
                // 捕获数据库更新异常，记录日志或返回错误信息
                // 这里可以记录详细的日志，例如 ex.InnerException.Message
                return BadRequest("Database update error: " + ex.Message);
            }
            catch (SqlException ex)
            {
                // 捕获SQL异常
                return BadRequest("SQL error: " + ex.Message);
            }
            catch (Exception ex)
            {
                // 捕获其他异常
                return BadRequest("General error: " + ex.Message);
            }

        }
        #region
        //[HttpPost]
        //public async Task<IHttpActionResult> UpdateData(int id)
        //{
        //    try
        //    {
        //        if (!Request.Content.IsMimeMultipartContent())
        //        {
        //            return BadRequest("Unsupported media type.");
        //        }

        //        var provider = new MultipartMemoryStreamProvider();
        //        await Request.Content.ReadAsMultipartAsync(provider);

        //        // 处理更新数据
        //        var salePart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Sale");
        //        if (salePart == null) return BadRequest("Missing Sale data");

        //        using (var context = new YourDbContext())
        //        using (var transaction = context.Database.BeginTransaction())
        //        {
        //            try
        //            {
        //                // 清理旧数据
        //                var existingBills = context.Sli_document_quality_standardBill.Where(b => b.fmainID == id);
        //                var existingEntries = context.Sli_document_quality_standardBillEntry.Where(e => e.fbillID == id);
        //                var existingAttachments = context.Sli_document_quality_standardAttachment.Where(a => a.fmainID == id);

        //                context.Sli_document_quality_standardBill.RemoveRange(existingBills);
        //                context.Sli_document_quality_standardBillEntry.RemoveRange(existingEntries);
        //                context.Sli_document_quality_standardAttachment.RemoveRange(existingAttachments);

        //                // 更新主表
        //                var saleJson = await salePart.ReadAsStringAsync();
        //                var standard = await context.Sli_document_quality_standard.FindAsync(id);
        //                if (standard == null) return NotFound();

        //                var updateData = JsonConvert.DeserializeObject<sli_document_quality_standard>(saleJson);
        //                context.Entry(standard).CurrentValues.SetValues(updateData);

        //                // 处理新子表数据
        //                var billPart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Bill");
        //                var billModels = billPart != null
        //                    ? JsonConvert.DeserializeObject<List<sli_document_quality_standardBill>>(await billPart.ReadAsStringAsync())
        //                    : new List<sli_document_quality_standardBill>();

        //                var entryPart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Entry");
        //                var entryModels = entryPart != null
        //                    ? JsonConvert.DeserializeObject<List<sli_document_quality_standardBillEntry>>(await entryPart.ReadAsStringAsync())
        //                    : new List<sli_document_quality_standardBillEntry>();

        //                billModels.ForEach(b => b.fmainID = id);
        //                entryModels.ForEach(e => e.fbillID = id);

        //                context.Sli_document_quality_standardBill.AddRange(billModels);
        //                context.Sli_document_quality_standardBillEntry.AddRange(entryModels);

        //                // 处理新附件
        //                var fileParts = provider.Contents.Where(c => c.Headers.ContentDisposition.Name.Trim('"') == "Files");
        //                foreach (var filePart in fileParts)
        //                {
        //                    var fileName = filePart.Headers.ContentDisposition.FileName.Trim('"');
        //                    var fileData = await filePart.ReadAsByteArrayAsync();
        //                    context.Sli_document_quality_standardAttachment.Add(new sli_document_quality_standardAttachment
        //                    {
        //                        fmainID = id,
        //                        fattachment = fileName,
        //                        fileData = fileData
        //                    });
        //                }

        //                await context.SaveChangesAsync();
        //                transaction.Commit();

        //                return Ok(new
        //                {
        //                    code = 200,
        //                    msg = "ok",
        //                    Id = id,
        //                    date = $"{id}更新成功"
        //                });
        //            }
        //            catch (Exception ex)
        //            {
        //                transaction.Rollback();
        //                return BadRequest($"Update failed: {ex.Message}");
        //            }
        //        }
        //    }
        //    catch (JsonException ex)
        //    {
        //        return BadRequest($"JSON parsing error: {ex.Message}");
        //    }
        //    catch (Exception ex)
        //    {
        //        return InternalServerError(ex);
        //    }
        //}

        // Delete和Get方法保持不变，已参考示例优化异常处理
        #endregion
        [System.Web.Http.HttpPost]
        public async Task<IHttpActionResult> UpdateData(int id)
        {
            try
            {
                if (!Request.Content.IsMimeMultipartContent())
                {
                    return BadRequest("Expected multipart/form-data request.");
                }

               


                using (var dbContext = new YourDbContext())
                {
                    var existingbill = dbContext.Sli_document_quality_standardBill.Where(b => b.fmainID == id);
                    dbContext.Sli_document_quality_standardBill.RemoveRange(existingbill);
                    var aa = existingbill.Select(b => b.id).ToList();
                    var existingEntry = dbContext.Sli_document_quality_standardBillEntry.Where(b => aa.Contains(b.fbillID));
                    dbContext.Sli_document_quality_standardBillEntry.RemoveRange(existingEntry);
                    var existingachment = dbContext.Sli_document_quality_standardAttachment.Where(b => b.fmainID == id);
                    dbContext.Sli_document_quality_standardAttachment.RemoveRange(existingachment);
                    dbContext.SaveChanges();

                    var provider = new MultipartMemoryStreamProvider();
                    var task = Request.Content.ReadAsMultipartAsync(provider);
                    //task.Wait();
                    await task;
                    foreach (var content in provider.Contents)
                    {
                        var sale = new sli_document_quality_standard();
                        var bill = new sli_document_quality_standardBill();
                        List<sli_document_quality_standardBillEntry> entryList = new List<sli_document_quality_standardBillEntry>();
                        List<sli_document_quality_standardBill> billList = new List<sli_document_quality_standardBill>();
                        List<sli_document_quality_standardAttachment> attachmentList = new List<sli_document_quality_standardAttachment>();
                        var entry = new sli_document_quality_standardBillEntry();
                        var attachment = new sli_document_quality_standardAttachment_view();


                        var contentDisposition = content.Headers.ContentDisposition;

                        if (contentDisposition.Name.Trim('\"').StartsWith("Sale"))
                        {
                            var keyValuePairs = contentDisposition.Name.Trim('\"').Substring("Sale".Length).Trim('[', ']').Split('=');
                            if (keyValuePairs.Length == 1)
                            {
                                var propertyName = keyValuePairs[0];
                                var propertyValue = content.ReadAsStringAsync().Result;

                                dynamic sale1 = JsonConvert.DeserializeObject(propertyValue);
                                var existing = dbContext.Sli_document_quality_standard.Find(id);
                                System.Diagnostics.Debug.WriteLine(propertyValue);
                                existing.Fnumber = sale1.Fnumber;
                                existing.Fname = sale1.Fname;
                                existing.Ftaxtrue = sale1.Ftaxtrue;
                                existing.FcustomerID = sale1.FcustomerID;
                                existing.Fdate = sale1.Fdate;
                                existing.FbillerID = sale1.FbillerID;
                                existing.FmaterialID = sale1.FmaterialID;
                                dbContext.SaveChanges();

                                var temp = sale1.sli_document_quality_standardAttachment_view;
                                if (temp.Count > 0)
                                {
                                    foreach (var tempitem in temp)
                                    {
                                        attachmentList.Add(new sli_document_quality_standardAttachment
                                        {
                                            fattachment = tempitem.fattachment,
                                            fileData = tempitem.fileData,
                                            fmainID = id
                                        });
                                        dbContext.Sli_document_quality_standardAttachment.AddRange(attachmentList);

                                    }
                                }


                            }
                        }
                        else if (contentDisposition.Name.Trim('\"').StartsWith("Files"))
                        {
                            if (contentDisposition.Name.Trim('\"').EndsWith("Files"))
                            {
                                var fileName = Path.GetFileName(content.Headers.ContentDisposition.FileName.Trim('\"'));
                                var fileData = content.ReadAsByteArrayAsync().Result;
                                attachmentList.Add(new sli_document_quality_standardAttachment
                                {
                                    fattachment = fileName,
                                    fileData = fileData,
                                    fmainID = id
                                });
                                dbContext.Sli_document_quality_standardAttachment.AddRange(attachmentList);
                                // dbContext.SaveChanges();

                                dbContext.SaveChanges();
                            }

                        }

                    }

                    var billPart = provider.Contents.FirstOrDefault(c => c.Headers.ContentDisposition.Name.Trim('"') == "Bill");

                    // 处理 Bill 数据
                    string billJson;
                    if (billPart != null)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            await billPart.CopyToAsync(ms);
                            ms.Seek(0, SeekOrigin.Begin);
                            billJson = new StreamReader(ms).ReadToEnd();
                        }
                    }
                    else
                    {
                        return BadRequest("Bill data is missing.");
                    }
                    var billModels = JsonConvert.DeserializeObject<List<sli_document_quality_standardBill_view>>(billJson);
                    System.Diagnostics.Debug.WriteLine(billModels);
                    System.Diagnostics.Debug.WriteLine(billJson);
                    System.Diagnostics.Debug.WriteLine(billPart);
                    // 添加主表数据

                    // 关联并添加中间表和子表数据
                    foreach (var bill1 in billModels)
                    {
                        var header = new sli_document_quality_standardBill
                        {
                            fmainID = id,
                            fnote = bill1.fnote,
                            fqualityOptionID = bill1.fqualityOptionID,
                            sli_document_quality_standardBillEntry = bill1.sli_document_quality_standardBillEntry_view.Select(d => new sli_document_quality_standardBillEntry
                            {
                                fbillID = bill1.id,
                                fmin = d.fmin,
                                fmax = d.fmax,
                                ftarget = d.ftarget,
                                fnoties = d.fnoties,
                                fnote = d.fnote,
                                fqualityObjectID = d.fqualityObjectID ,
                                fexplanation = d.fexplanation
                            }).ToList()
                        };
                        dbContext.Sli_document_quality_standardBill.Add(header);
                    }
                    dbContext.SaveChanges();



                    var data = new
                    {
                        code = 200,
                        msg = "ok",
                        Id = id,
                        date = id + "修改成功"

                    };

                    return Ok(data);




                }
            }
            catch (Exception ex)
            {
                return Ok(ex.ToString());
            }


        }

        [System.Web.Http.HttpPost]
        public async Task<object> Delete(List<int> id)
        {
            try
            {
                foreach (var deleteid in id)
                {
                    var context = new YourDbContext();
                    var entity = await context.Sli_document_quality_standard.FindAsync(deleteid);
                    if (entity == null)
                    {
                        var dataNull = new
                        {
                            code = 200,
                            msg = "ok",
                            Id = id.ToString(),
                            date = id.ToString() + "不存在"
                        };
                        //string json = JsonConvert.SerializeObject(data);
                        return dataNull;
                    }

                    var existingbill = context.Sli_document_quality_standardBill.Where(b => b.fmainID == deleteid);
                    context.Sli_document_quality_standardBill.RemoveRange(existingbill);
                    var existingEntry = context.Sli_document_quality_standardBillEntry.Where(b => b.fbillID == deleteid);
                    context.Sli_document_quality_standardBillEntry.RemoveRange(existingEntry);
                    var existingachment = context.Sli_document_quality_standardAttachment.Where(b => b.fmainID == deleteid);
                    context.Sli_document_quality_standardAttachment.RemoveRange(existingachment);
                    context.Sli_document_quality_standard.RemoveRange(entity);
                    await context.SaveChangesAsync();

                }

                // var data = new { Status = "Success", Message = "Data retrieved successfully", Data = new { /* actual data here */ } };
                var data = new
                {
                    code = 200,
                    msg = "Success",
                    //orderId = id.ToString(),
                    date = "删除成功"
                };
                return data;
            }
            catch (Exception ex)
            {
                var data = new
                {
                    code = 400,
                    msg = "失败",
                    orderId = id.ToString(),
                    date = ex.ToString()
                };
                return data;
            }


        }

        [HttpGet]
        public IHttpActionResult GetTableBydocument_tech_saleAttachment(int? id = null)
        {
            try
            {
                var context = new YourDbContext();

                var attachment = context.Sli_document_quality_standardAttachment.FirstOrDefault(a => a.id == id);
                if (attachment == null)
                {
                    return NotFound();
                }

                // 将字节数组转换为流
                var stream = new MemoryStream(attachment.fileData);
                // 返回文件流作为响应，并设置适当的内容类型和文件名
                var response = new HttpResponseMessage()
                {
                    Content = new StreamContent(stream),
                    StatusCode = HttpStatusCode.OK
                };
                response.Content.Headers.ContentType = new MediaTypeHeaderValue(GetContentType(attachment.fattachment));
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline")
                {
                    FileName = attachment.fattachment
                };

                return ResponseMessage(response);
                // 返回文件流作为响应



            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }


        }

        private string GetContentType(string fileName)
        {
            var extension = System.IO.Path.GetExtension(fileName);
            switch (extension)
            {
                case ".pdf":
                    return "application/pdf";
                case ".jpg":
                case ".jpeg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                case ".doc":
                    return "application/msword";
                case ".docx":
                    return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                // 添加更多文件类型的处理
                default:
                    return "application/octet-stream";
            }
        }

        [HttpGet]
        public IHttpActionResult GetTableBydocument_quality_standard(int page = 1, int pageSize = 10, string fnumber = null, string fname = null)
        {
            try
            {
                var context = new YourDbContext();
                IQueryable<sli_document_quality_standard_view> query = context.Sli_document_quality_standard_view;

                if (!string.IsNullOrEmpty(fnumber))
                {
                    query = query.Where(q => q.Fnumber.Contains(fnumber));
                }

                if (!string.IsNullOrEmpty(fname))
                {
                    query = query.Where(q => q.Fname.Contains(fname));
                }
                var totalCount = query.Count(); //记录数
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); // 页数
                var paginatedQuery = query.OrderByDescending(b => b.Id).Skip((page - 1) * pageSize).Take(pageSize); //  某页记录
                                                                                                                    //var datas = query.ToList();
                var response = new    // 定义 前端返回数据  总记录，总页，当前页 ，size,返回记录
                {
                    code = 200,
                    msg = "OK",
                    data = new
                    {
                        totalCounts = totalCount,
                        totalPagess = totalPages,
                        currentPages = page,
                        pageSizes = pageSize,
                        data = paginatedQuery
                    }


                };

                return Json(response);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }
        [HttpGet]
        public IHttpActionResult GetTableBydocument_quality_standardall(int? id = null)
        {
            try
            {
                using (var context = new YourDbContext())
                {
                    // 获取主表数据
                    var mainEntity = context.Sli_document_quality_standard_view
                        .FirstOrDefault(m => m.Id == id);

                    if (mainEntity == null)
                    {
                        return NotFound();
                    }

                    // 获取所有关联的Bill数据
                    var bills = context.Sli_document_quality_standardBill_view
                        .Where(b => b.fmainID == id)
                        .ToList();

                    // 获取所有关联的Entry数据
                    var entries = context.Sli_document_quality_standardBillEntry_view
                        .Where(e => e.fbillID == id)
                        .ToList();

                    // 构建嵌套结构
                    var billViewModels = bills.Select(b => new
                    {
                        Id = b.id,
                        fmainID = b.fmainID,
                        fqualityOptionID = b.fqualityOptionID,
                        fnote = b.fnote,
                        Entries = entries
                            .Where(e => e.fbillID == b.id) // 根据Bill的ID关联Entry
                            .Select(e => new
                            {
                                e.id,
                                e.fbillID,
                                e.fqualityObjectID,
                                e.fmax,
                                e.fmin,
                                e.ftarget,
                                e.fnote,
                                e.fnoties,
                                e.fexplanation
                            })
                            .ToList()
                    }).ToList();

                    // 获取附件
                    var attachments = context.Sli_document_quality_standardAttachment_view
                        .Where(a => a.fmainID == id)
                        .ToList();

                    // 构建最终响应对象
                    var result = new
                    {
                        Sli_document_quality_standard = new
                        {
                            mainEntity.Id,
                            mainEntity.Fnumber,
                            mainEntity.Fname,
                            mainEntity.Fdate,
                            mainEntity.FbillerID,
                            mainEntity.Fstatus,
                            mainEntity.FcustomerID,
                            mainEntity.FmaterialID,
                            mainEntity.ForderNo,
                            mainEntity.ForderEntryID,
                            mainEntity.FstandardNo,
                            mainEntity.Ftaxtrue,
                            mainEntity.FmaterialName,
                            mainEntity.FcustomerName,
                            mainEntity.FSumNumber,
                            sli_document_quality_standardBill_view = billViewModels,
                            sli_document_quality_standardAttachment_view = attachments
                        }
                    };

                    return Ok(new
                    {
                        code = 200,
                        msg = "OK",
                        data = new { data = new[] { result } }
                    });
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(new Exception($"查询失败: {ex.Message}"));
            }
        }

        public IHttpActionResult GetDocprocessAll(int? id = null)
        {
            try
            {
                var context = new YourDbContext();




                var quality_standard = context.Sli_document_quality_standard_view.Find(id);
                //var Fbillid = techSale.sli_document_process_modelBill_view.Where();
                // var modelBill = context.Sli_document_process_modelBillEntry_view.Find(id);

                quality_standard.sli_document_quality_standardBill_view = context.Sli_document_quality_standardBill_view.Where(st1 => st1.fmainID == id).ToList() ?? new List<sli_document_quality_standardBill_view>();
                if (quality_standard.sli_document_quality_standardBill_view != null)
                {
                    foreach (var bill in quality_standard.sli_document_quality_standardBill_view)
                    {
                        bill.sli_document_quality_standardBillEntry_view = context.Sli_document_quality_standardBillEntry_view.Where(st2 => st2.fbillID == bill.id).ToList() ?? new List<sli_document_quality_standardBillEntry_view>();
                    }
                }

                quality_standard.sli_document_quality_standardAttachment_view = context.Sli_document_quality_standardAttachment_view.Where(st3 => st3.fmainID == id).ToList() ?? new List<sli_document_quality_standardAttachment_view>();



                var result = new List<object>();



                result.Add(new
                {
                    Sli_document_quality_standard = quality_standard,

                });

                var response = new    // 定义 前端返回数据  总记录，总页，当前页 ，size,返回记录
                {
                    code = 200,
                    msg = "OK",
                    data = new
                    {

                        data = result
                    }
                };

                return Ok(response);





            }
            catch (Exception ex)
            {
                return Ok(ex.ToString());
            }
        }

        //---------------------%%%%%%%%%%%%%%%%%%%%%%%%%%%%------------------------------
    }
}
